var userManager_page = {};

userManager_page.action = {
    initBody: function () {
        userManager_page.interface.initGroupTree();
        userManager_page.interface.initTablePage();
        userManager_page.action.bindEvent();
    },
    bindEvent: function () {
        $("#addBtn").click(function () {
            userManager_page.interface.openFormPage();
            return false;
        });
        // $("#cancel").click(function () {
        //     userManager_page.action.initBody();
        //     return false;
        // });
        // $("#groupName").click(function () {
        //     userManager_page.interface.initGroupPage();
        //     return false;
        // });
        // $("#submitBtn").click(function () {
        //     userManager_page.action.saveBtnClick();
        //     return false;
        // });
    },
    // bindEventClose:function () {
    //     $(".close").click(function(){
    //         this.remove();
    //     })
    // },
    // 在做action动作时校验数据data
    // checkData:function (action, data) {
    //     var result = AppComm.data.newResult();
    //
    //     if (data.groupId==""||data.groupId==null||data.groupId.trim()==""){
    //         result.code = Enums.ResultEnum().FAILURE.code;
    //         result.msg = "所属组织不能为空。";
    //         return result;
    //     }
    //     if (action=='addSubmit') {
    //         if (data.username==""||data.username==null||data.username.trim()==""){
    //             result.code = Enums.ResultEnum().FAILURE.code;
    //             result.msg = "账号不能为空。";
    //             return result;
    //         }
    //     }
    //
    //     var flag = 0;
    //     var params={
    //         id:data.id,
    //         operationKey:data.operationKey,
    //     };
    //     var onSuccess = function (resultData) {
    //         if (resultData.code==Enums.ResultEnum().SUCCESS.code) {
    //             if(resultData.data!=null){
    //                 flag++;
    //             }
    //         }
    //     };
    //
    //     var checkUrl = "";
    //     if (action=='editSubmit') {
    //         checkUrl = AppComm.url.getBaseURL()+'/userManager/ajax/getUserByUserNameOutCurrent';
    //     } else if (action=='addSubmit'){
    //         checkUrl = AppComm.url.getBaseURL()+'/userManager/ajax/getUserByUserName';
    //     }
    //
    //     AppComm.ajax.execute({
    //         'url':checkUrl,
    //         'data':params,
    //         'async':false,
    //         'success':onSuccess
    //     });
    //
    //     if(flag>0){
    //         result.code = Enums.ResultEnum().FAILURE.code;
    //         result.msg = "该账号已存在。";
    //     } else {
    //         result.code = Enums.ResultEnum().SUCCESS.code;
    //     }
    //     return result;
    // },
    // saveBtnClick:function () {
    //     var params = {
    //         id:$("#id").val(),
    //         pswd:$("#pswd").val(),
    //         username:$("#username").val(),
    //         fullname:$("#fullname").val(),
    //         phone:$("#phone").val(),
    //         email:$("#email").val(),
    //         comment:$("#comment").val(),
    //         orderId:$("#orderId").val(),
    //         groupId:$("#groupId").val(),
    //         groupName:$("#groupName").val(),
    //         theme:$("#theme").val(),
    //     };
    //     var result = userManager_page.action.checkData(userManager_page.data.action, params);
    //     if (result.code==Enums.ResultEnum().FAILURE.code) {
    //         AppComm.layer.warm(result.msg);
    //     } else {
    //         var onSuccess = function (resultData) {
    //             if (resultData.code==Enums.ResultEnum().SUCCESS.code) {
    //                 userManager_page.action.initBody();
    //                 AppComm.notice.success('保存成功！');
    //             } else {
    //                 AppComm.notice.error('保存失败！');
    //             }
    //         };
    //         AppComm.ajax.execute({
    //             'url':AppComm.url.getBaseURL()+'/userManager/ajax/saveUser',
    //             'data':params,
    //             'success':onSuccess
    //         });
    //     }
    // },
    deleteUser: function (userId) {
        AppComm.ajax.post('/userManager/ajax/deleteUser', {
            id: userId
        }, function (resultData) {
            userManager_page.data.tableIns.reload();
            AppComm.ajax.onSuccess(resultData);
        });
    },
    saveRoles: function (currUserid, roleIds) {
        var roleD = new Array();
        for (var i=0; i<roleIds.length; i++) {
            roleD.push(roleIds[i].value);
        }
        var ids = roleD.join(",");

        AppComm.ajax.post('/roleManager/ajax/saveRolePer', {
            userId:currUserid,
            roleIds:ids
        });
    }
};
userManager_page.interface = {
    // 加载组织树
    initGroupTree: function() {
        var groupTree = new ztreeUnit('groupTree', '/groupManager/ajax/getGroupZtree', {});
        groupTree.options.isExpandAll = true;
        groupTree.ztreeInit();
        groupTree.setZtreeCallback(function (event, treeId, treeNode) {
            userManager_page.data.parentGroupId = treeNode.id;
            userManager_page.data.tableIns.reload({
                where:{
                    page: 1,
                    parentGroupId:userManager_page.data.parentGroupId,
                    fullname: $("#fullnameInput").val()
                }
            });
        });
    },
    // 加载表格页
    initTablePage: function () {
        var html = template("userManagerList_template");
        $(".userManager_box").html(html);

        layui.use(['table', 'form'], function () {
            var table = layui.table;

            //执行表格渲染
            var tableIns = table.render({
                height: 625,
                url: AppComm.url.getBaseURL() + '/userManager/ajax/getUserManagerList',
                elem: "#tb_list",
                page: true,
                limit: 14,
                limits: [14, 28, 42],
                loading: true,
                method: 'POST',
                contentType: 'application/json',
                id: 'id',
                cols: [[
                    {
                        field: 'fullname',
                        title: '姓名',
                        //width:200,
                        align: 'left',
                        width:150
                    },
                    {
                        field: 'username',
                        title: '账号',
                        align: 'left',
                        width:100
                    }, {
                        field: 'phone',
                        title: '电话',
                        align: 'left',
                        width:130
                    }, {
                        field: 'email',
                        title: '邮箱',
                        align: 'left',
                        width:150
                    }, {
                        field: 'orderId',
                        title: '排序号',
                        edit: 'text',
                        align: 'left',
                        width:80
                    },{
                        field: 'groupName',
                        title: '所属组织',
                        align: 'left',
                        width:120
                    },
                    {
                        field: 'comment',
                        title: '说明',
                        align: 'left',
                        width:100
                    }, {
                        field: 'operation',
                        title: '操作',
                        fixed: 'right',
                        width: 265,
                        toolbar: '#toolbar'
                    }
                ]]
            });

            userManager_page.data.tableIns = tableIns;

            table.on('tool(tb_list)', function (obj) {
                var rowData = obj.data;
                var layEvent = obj.event;
                if (layEvent === 'editBtn') {
                    userManager_page.interface.openFormPage(rowData.id);
                }
                if (layEvent === 'perBtn') {
                    userManager_page.interface.initPermissionPage(rowData.id);
                    // userManager_page.action.bindEvent();
                }
                if (layEvent === 'deleteBtn') {
                    // if(rowData.username=="admin"){
                    //     layer.msg("管理员账号不能删除！！",{icon: 2});
                    // }else{
                        AppComm.layer.confirm('确定要进行删除吗？',function () {
                            userManager_page.action.deleteUser(rowData.id);
                        });
                    // }
                };
                if (layEvent === 'showPer') {
                    AppComm.ajax.post('/userManager/ajax/getPermissionListByUserId', {
                        id:rowData.id,
                    }, function (resultData) {
                        if (resultData.code==Enums.ResultEnum().SUCCESS.code) {
                            var html = template("userManagerList_per", {});
                            var perLayer = layer.open({
                                type: 1,
                                // skin: 'layui-layer-rim', //加上边框
                                area: ['800px', '760px'], //宽高
                                offset: '100px',
                                shadeClose: true,
                                content: html
                            });
                            var myChart = echarts.init(document.getElementById('treePer'));
                            myChart.showLoading();
                            var data1 = {
                                "name": "菜单",
                                "children": resultData.data.menu
                            };
                            var data2 = {
                                "name": "操作",
                                "children": resultData.data.permission
                            };
                            myChart.hideLoading();

                            myChart.setOption(option = {
                                tooltip: {
                                    trigger: 'item',
                                    triggerOn: 'mousemove'
                                },
                                legend: {
                                    top: '2%',
                                    left: '3%',
                                    orient: 'vertical',
                                    data: [{
                                        name: '菜单',
                                        icon: 'rectangle'
                                    } ,
                                        {
                                            name: '操作',
                                            icon: 'rectangle'
                                        }],
                                    borderColor: '#c23531'
                                },
                                series:[
                                    {
                                        type: 'tree',
                                        name: '菜单',
                                        data: [data1],
                                        top: '5%',
                                        left: '7%',
                                        bottom: '2%',
                                        right: '60%',

                                        symbolSize: 7,

                                        label: {
                                            normal: {
                                                position: 'left',
                                                verticalAlign: 'middle',
                                                align: 'right'
                                            }
                                        },

                                        leaves: {
                                            label: {
                                                normal: {
                                                    position: 'right',
                                                    verticalAlign: 'middle',
                                                    align: 'left'
                                                }
                                            }
                                        },

                                        expandAndCollapse: true,
                                        animationDuration: 550,
                                        animationDurationUpdate: 750

                                    },
                                    {
                                        type: 'tree',
                                        name: '操作',
                                        data: [data2],

                                        top: '20%',
                                        left: '60%',
                                        bottom: '22%',
                                        right: '18%',

                                        symbolSize: 7,

                                        label: {
                                            normal: {
                                                position: 'left',
                                                verticalAlign: 'middle',
                                                align: 'right'
                                            }
                                        },

                                        leaves: {
                                            label: {
                                                normal: {
                                                    position: 'right',
                                                    verticalAlign: 'middle',
                                                    align: 'left'
                                                }
                                            }
                                        },

                                        expandAndCollapse: true,

                                        animationDuration: 550,
                                        animationDurationUpdate: 750
                                    }
                                ]
                            });
                        }
                    });

                }
            });
            table.on('edit(tb_list)', function(obj){
                AppComm.ajax.post('/userManager/ajax/saveUser', {
                    id:obj.data.id,
                    orderId:obj.value,
                }, function (resultData) {
                    AppComm.ajax.onSuccess(resultData);
                    userManager_page.action.initBody();
                });
            });
            // 查询
            var form = layui.form;
            form.render(null, 'searchForm');
            form.on('submit(searchBtn)', function (data) {
                var postData = {
                    fullname: data.field.fullnameInput
                };
                tableIns.reload({
                    page: {curr:1},
                    where: postData
                });
                return false;
            });
        });

    },
    openFormPage:function(rowId) {
        AppComm.layer.open('/manager/form/userManagerForm', null, function (layero, index) {
            var iframeWin = AppComm.utils.iframeWin(layero);
            if (rowId != undefined && '' != rowId.trim()) {
                iframeWin.userManagerForm_page.data.rowId = rowId;
            }
            iframeWin.userManagerForm_page.action.initBody();
        });
    },
    //角色授权界面初始化
    initPermissionPage: function (dataId) {
        var html = template("userManagerList_role", {});
        var roleLayer = layer.open({
            type: 1,
            // skin: 'layui-layer-rim', //加上边框
            area: '480px', //宽高
            offset: '50px',
            content: html,
            btnAlign: 'c',
            btn: ['提交', '取消'], //可以无限个按钮
            yes: function(index, layero){
                layer.close(roleLayer);
                var getData = userManager_page.data.transfer.getData("transferId");
                userManager_page.action.saveRoles(dataId, getData);
            },
        });
        AppComm.ajax.post('/roleManager/ajax/getRolesTransfer4User', {
            id:dataId
        }, function (resultData) {
            if (resultData.code==Enums.ResultEnum().SUCCESS.code) {
                layui.use(['transfer', 'layer', 'util'], function(){
                    var $ = layui.$
                        ,transfer = layui.transfer
                        ,layer = layui.layer
                        ,util = layui.util;
                    userManager_page.data.transfer = transfer;
                    userManager_page.data.transfer.render({
                        id:'transferId',
                        elem: '#transfer',
                        title: ['未授权角色', '已授权角色'],
                        data: resultData.data.allRoles,
                        value: resultData.data.haveRoles
                    })

                });
            }
        });
    },
};

userManager_page.data = {
    'tableIns': undefined,
    roleTable:null,
    imgUpload:null,
    'currGroupId':'',
    'action':"",
    transfer : null,
    parentGroupId:0
};

AppComm.initFrame(userManager_page);